package com.cjx.leetcode.backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author cjx
 * @description E51.N皇后【难】
 * @createDate 2024/4/8 10:49
 **/
public class E51 {

    private List<List<String>> result = new ArrayList<>();

    public List<List<String>> solveNQueens(int n) {
        char[][] chessboard = new char[n][n];
        for (char[] chars : chessboard) {
            Arrays.fill(chars,'.');
        }
        backtracking(chessboard, 0,n);
        return result;
    }

    private void backtracking(char[][] chessboard, int row,int n) {
        if (row == n) {
            result.add(arrayToList(chessboard));
            return;
        }
        for (int col = 0; col < n; col++) {
            //判断当前位置是否可以放皇后
            if (isPutItDown(row, col, chessboard,n)) {
                chessboard[col][row] = 'Q';
                backtracking(chessboard, row + 1,n);
                chessboard[col][row] = '.';
            }
        }
    }

    private List<String> arrayToList(char[][] chessboard) {
        List<String> list = new ArrayList<>();
        for (char[] c : chessboard) {
            list.add(String.copyValueOf(c));
        }
        return list;
    }

    private boolean isPutItDown(int row, int col, char[][] chessboard,int n) {
        //纵坐标是否有皇后
        for (int i = 0; i < row; i++) {
            if (chessboard[i][col] == 'Q') {
                return false;
            }
        }
        //135°角是否有皇后
        for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
            if (chessboard[i][j] == 'Q') {
                return false;
            }
        }
        //45°角是否有皇后
        for (int i = row - 1, j = col + 1; i >= 0 && j <= n - 1; i--, j++) {
            if (chessboard[i][j] == 'Q') {
                return false;
            }
        }
        return true;
    }

}
